#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#define BUF_SIZE 1024
#define DEVICE_NAME "sda" // 替换成你要监视的磁盘设备名

struct disk_stats {
    unsigned long long reads;
    unsigned long long writes;
};

void read_disk_stats(struct disk_stats *stats) {
    FILE *fp;
    char buffer[BUF_SIZE];
    char device[32];
    unsigned long long reads, writes;

    sprintf(device, " %s ", DEVICE_NAME);

    fp = fopen("/proc/diskstats", "r");
    if (fp == NULL) {
        perror("Error opening /proc/diskstats");
        exit(EXIT_FAILURE);
    }

    while (fgets(buffer, sizeof(buffer), fp) != NULL) {
        if (strstr(buffer, device)) {
            sscanf(buffer, "%*d %*d %*s %*d %*d %*d %*d %*d %*d %*d %*d %llu %*d %*d %*d %llu", &reads, &writes);
            stats->reads = reads;
            stats->writes = writes;
            break;
        }
    }

    fclose(fp);
}

int main() {
    struct disk_stats prev_stats, curr_stats;
    unsigned long long prev_reads, prev_writes, curr_reads, curr_writes;
    double read_speed, write_speed;

    while (1) {
        read_disk_stats(&prev_stats);
        prev_reads = prev_stats.reads;
        prev_writes = prev_stats.writes;

        sleep(1); // 等待一秒钟

        read_disk_stats(&curr_stats);
        curr_reads = curr_stats.reads;
        curr_writes = curr_stats.writes;

        // 计算读写速率
        read_speed = (curr_reads - prev_reads) / 1024.0; // 转换成 KB/s
        write_speed = (curr_writes - prev_writes) / 1024.0;

        printf("Read speed: %.2f KB/s\t Write speed: %.2f KB/s\n", read_speed, write_speed);
    }

    return 0;
}
